import React from 'react'
import { ScrollView, View, KeyboardAvoidingView, Image } from 'react-native'
import { Metrics, Colors } from '../../Themes'
import { API, WINDOW } from '../../Services'
import styles from '../Styles/CommonContainerStyles'
import Button from 'apsl-react-native-button'
import { List, InputItem} from '@ant-design/react-native'
const ListItem = List.Item
import ImagePicker_mult from 'react-native-image-crop-picker'
import LdImage from '../../Components/LdImage'


class SelfInfoScreen extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            ...WINDOW.loginUser,
            localImage:null,
        }
    }

    componentDidMount() {
        this._fetch_selectUserInfo()
    }

    _fetch_selectUserInfo() {
        API.selectUserInfo({id:this.state.id})
            .then((response) => {
                const { ok, data } = response
                if (ok && data.code === 1) {
                    let userData = data.data
                    this.setState({ ...userData })
                }
            })   
    }

    _fetch_Add() {
        if (!this.state.mobile) {
            return WINDOW.showToast('手机号不能为空！')
        }
        const { avatar, address, sex, user_nickname, mobile, id } = this.state
        let user = { avatar, address, sex, user_nickname, mobile, id }
        let key = WINDOW.showToastLoad()
        API.editUserInfo(user).then((response) => {
            WINDOW.hideToast(key)
            const { ok, data } = response
            if (ok && data.code === 1) {
                let loginUser = { ...user, token: WINDOW.loginUser.token }
                WINDOW.loginUser = loginUser
                WINDOW.showToastSuccess('修改成功')
                this.props.route.params?.callBack(loginUser)
                this.props.navigation.popToTop()
            } else {
                return WINDOW.showToastError('请求失败！')
            }
        })
    }


    //上传图片
    _uploadImage = () => {
        let imag = [this.state.localImage]
        let key = WINDOW.showToastLoad()
        API.uploadImage(imag).then((response) => {
            WINDOW.hideToast(key)
            const { ok, data } = response
            if (ok && data.code === 1) {
                let file = data?.data
                this.setState({ avatar: file.filepath }, () => this._fetch_Add())
            } else {
                return WINDOW.showToastError('请求失败！')
            }
        })
    }

    _doAdd = () => {
        console.log(this.state)
        if (this.state.localImage) {
            this._uploadImage()
        } else {
            this._fetch_Add()
        }
    }

    _selectImageCallback = (image) => {
        this.setState({ image }, () => this._fetch_Add())
    }

    _doSelectCity = () => {
        this.props.navigation.navigate('CitySelect', { callBack: this._callBack })
    }
    _callBack = (item) => {
        this.setState({ address: item.areaName })
    }

    _selectPhoto() {
        let BUTTONS = ['拍摄', '从手机相册选择', '取消']
        WINDOW.showActionSheet(
            {
                title: '选择',
                options: BUTTONS,
                cancelButtonIndex: BUTTONS.length - 1,
            },
            buttonIndex => {
                if (buttonIndex === BUTTONS.length - 1) {
                    return
                } else if (buttonIndex === 0) {
                    this._selectFromCamera()
                } else if (buttonIndex === 1) {
                    this._selectFromPhoto()
                }
            },
        )
    }
    _selectFromPhoto() {
        ImagePicker_mult.openPicker({
            multiple: false,
            width: 300,
            height: 300,
            cropping: true,
            cropperCircleOverlay: true,
        }).then(images => {
            console.log(images)
            this.setState({ localImage: images })
        });
    }
    _selectFromCamera() {
        ImagePicker_mult.openCamera({
            width: 300,
            height: 300,
            cropping: true,
            cropperCircleOverlay: true,
        }).then(image => {
            console.log(image);
            this.setState({ localImage: image })
        });
    }



    _renderFooter = () => (
        <Button
            onPress={this._doAdd}
            style={{ width: Metrics.screenWidth - 15 * 2, height: 48, alignSelf: 'center', backgroundColor: Colors.mainColor, marginTop: 15, borderWidth: 0, borderRadius: 3 }}
            textStyle={{ color: 'white', fontSize: 18, fontWeight: 'bold' }}>
            修改
        </Button>
    )

    _renderContent = () => {
        return (
            <List renderHeader={null}>
                <ListItem arrow="horizontal" extra={
                    this.state.localImage ?
                        <Image source={{ uri: this.state.localImage.path }} style={{ width: 50, height: 50, marginVertical: 10 }} /> :
                        <View style={{ marginVertical: 10 }}>
                            <LdImage url={this.state.avatar} style={{ width: 50, height: 50 }} />
                        </View>
                }
                    arrow="horizontal" onPress={this._selectPhoto.bind(this)}>头像</ListItem>
                <InputItem
                    clear
                    value={this.state.user_nickname}
                    onChange={user_nickname => {
                        this.setState({
                            user_nickname,
                        });
                    }}
                    placeholder="输入昵称">昵称</InputItem>
                <ListItem arrow="horizontal" wrap extra={this.state.sex === 0 ? '男' : '女'} multipleLine onPress={() => {
                    let BUTTONS = ['男', '女', '取消']
                    WINDOW.showActionSheet(
                        {
                            title: '选择类别',
                            options: BUTTONS,
                            cancelButtonIndex: BUTTONS.length - 1,
                        },
                        buttonIndex => {
                            if (buttonIndex === BUTTONS.length - 1) {
                                return
                            }
                            this.setState({ sex: buttonIndex })
                        },
                    )
                }}>性别</ListItem>
                <InputItem
                    clear
                    type='number'
                    editable={false}
                    value={this.state.mobile}
                    onChange={mobile => {
                        this.setState({
                            mobile,
                        });
                    }}
                    placeholder="输入手机号" >手机号</InputItem>
                <ListItem arrow="horizontal" wrap extra={this.state.address || "请选择地区"} multipleLine onPress={this._doSelectCity}>地区</ListItem>
            </List>
        )
    }
    render() {
        return (
            <View style={styles.container}>
                <KeyboardAvoidingView behavior={Metrics.isIOS ? 'padding' : null} style={{ flex: 1 }} >
                    <ScrollView keyboardShouldPersistTaps='handled'>
                        {this._renderContent()}
                        {this._renderFooter()}
                    </ScrollView>
                </KeyboardAvoidingView>

            </View>
        )
    }
}


export default SelfInfoScreen
